<?php

declare(strict_types=1);

namespace App\Admin;

use App\Entity\Paths;
use App\Entity\Tags;
use App\Library\Admin\MyAdmin;
use App\Library\Helper\GeneralHelper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Route\RouteCollection;
use Sonata\AdminBundle\Show\ShowMapper;

final class TagsAdmin extends MyAdmin
{

    protected function configureDatagridFilters(DatagridMapper $datagridMapper): void
    {
        $datagridMapper
            ->add('name')
            ->add('docUrl');
    }

    protected function configureListFields(ListMapper $listMapper): void
    {
        $listMapper
            ->addIdentifier('name', null, [
                'header_style' => 'width: 20%'
            ])
            ->add('description',null, [
                'header_style' => 'width: 70%'
            ]);
    }

    protected function configureFormFields(FormMapper $formMapper): void
    {
        $formMapper
            ->add('name')
            ->add('description')
            ->add('docDescription')
            ->add('docUrl');
    }

    protected function configureShowFields(ShowMapper $showMapper): void
    {
        $showMapper
            ->add('id')
            ->add('name')
            ->add('description')
            ->add('docDescription')
            ->add('docUrl');
    }

    public function prePersist($object)
    {
        parent::prePersist($object); // TODO: Change the autogenerated stub

        $object->setInfoId(GeneralHelper::getInstance()->info_id);
        $object->setCreatedAt(new \DateTime());
    }

    public function preRemove($object)
    {
        parent::preRemove($object); // TODO: Change the autogenerated stub

        // 删除时校验
        $path = $this->modelManager->findOneBy(Paths::class, ['infoId' => GeneralHelper::getInstance()->info_id]);
        if (is_object($path)) {
            GeneralHelper::getOneInstance()->addFlash('sonata_flash_error', '该标签有接口关联，不能被删除');
            $url = $this->generateUrl('list', $this->getFilterParameters());
            header("Location:" . $url);
            exit();
        }
    }

    public function preBatchAction($actionName, ProxyQueryInterface $query, array &$idx, $allElements)
    {
        switch ($actionName) {
            case 'delete':
                $this->verifyInfo(Tags::class, $idx, $allElements);

                // 删除时校验
                if ($allElements) {
                    $tag_ids = GetterHelper::getEntityManager()->getRepository(Tags::class)->getTagIds(GeneralHelper::getInstance()->info_id);
                } else {
                    $tag_ids = $idx;
                }
                $paths = $this->modelManager->findBy(Paths::class, ['tagId' => $tag_ids]);
                if (count($paths) > 0) {
                    GeneralHelper::getOneInstance()->addFlash('sonata_flash_error', '所选择的数据有标签关联接口，不能被执行批量删除操作');
                    $url = $this->generateUrl('list', $this->getFilterParameters());
                    header("Location:" . $url);
                    exit();
                }

                break;
        }

        parent::preBatchAction($actionName, $query, $idx, $allElements); // TODO: Change the autogenerated stub
    }

    public function postPersist($object)
    {
        parent::postPersist($object); // TODO: Change the autogenerated stub

        // 是否自动更新文档
        GeneralHelper::getOneInstance()->buildCurrentInfoApiConfig();
    }

    public function postUpdate($object)
    {
        parent::postUpdate($object); // TODO: Change the autogenerated stub

        // 是否自动更新文档
        GeneralHelper::getOneInstance()->buildCurrentInfoApiConfig();
    }

    public function postRemove($object)
    {
        parent::postRemove($object); // TODO: Change the autogenerated stub

        // 是否自动更新文档
        GeneralHelper::getOneInstance()->buildCurrentInfoApiConfig();
    }

    public function createQuery($context = 'list')
    {
        $query = parent::createQuery($context); // TODO: Change the autogenerated stub

        $query->andWhere(
            $query->expr()->eq($query->getRootAliases()[0] . '.infoId', ':infoId')
        );
        $query->setParameter('infoId', GeneralHelper::getInstance()->info_id);

        return $query;
    }

    protected function configureRoutes(RouteCollection $collection)
    {
        parent::configureRoutes($collection); // TODO: Change the autogenerated stub
        $collection->remove('export');
        $collection->remove('show');
    }
}
